// Algebraic compression.cpp : Defines the entry point for the console application.
//
#pragma once
#include "stdafx.h"
#include <conio.h>
#include <ctime>
#include "Ar.h"
#include "Model.h"
#include <fstream>
#include "iostream"
using namespace std;

#define length 3

FILE *infile, *outfile;

void encode (void)
{
	int c, success = 0, k = 0;
	int *context;
	Link *match;
	Model M(length);
	context = new int [length+1];
	for (int i = 0; i <= length; i++)
	{
		context[i] = '\0';
	}
	start_model(0);
	while ((c = getc(infile)) != EOF)
	{
		for (int i = length; i > 0; i--)
			context[i] = context[i-1];
		context[0] = c;
		match = M.Encode_sym(c, context);
		M.Update(c, context, match);
	}
	for (int i = length; i > 0; i--)
		context[i] = context[i-1];
	context[0] = 256;
	M.Encode_sym(256, context);
	done_encoding ();
	done_outputing_bits ();
	fclose (infile);
}

void decode()
{
	int c, success = 1;
	int *context;
	Link *match;
	Model M(length);
	context = new int [length+1];
	for (int i = 0; i <= length; i++)
	{
		context[i] = '\0';
	}
	start_model(1);
	while (success)
	{
		for (int i = length; i > 0; i--)
			context[i] = context[i-1];
		match = M.Decode(context, c);
		if (c == 256)
			break;
		putc (c, outfile);
		context[0] = c;
		M.Update (c, context, match);
	}
	fclose (outfile);
}

void main()
{
	clock_t start,end;
	infile = fopen ("infile.txt", "r+b");
	outfile = fopen("outfile.txt", "w+b");
	if (infile == NULL || outfile == NULL)
	{
		cout << "Error!";
		getch();
		exit(0);
	}
	start = clock();
	encode();
	end = clock();
	cout << (float)(end-start)/CLOCKS_PER_SEC<<endl;
	start = clock();
	decode();
	end = clock();
	cout << (float)(end-start)/CLOCKS_PER_SEC;
	getch();
}


